package com.StarStudio.Service.Impl;

import cn.hutool.core.util.IdUtil;
import com.StarStudio.DAO.CouponsDAO;
import com.StarStudio.DAO.CouponsStockDAO;
import com.StarStudio.DAO.PanicBuyingCouponsDAO;
import com.ruoyi.common.core.Entity.*;
import com.StarStudio.Service.CouponsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CouponsServiceImpl implements CouponsService {

    @Autowired
    CouponsDAO couponsDAO;

    @Autowired
    CouponsStockDAO couponsStockDAO;

    @Autowired
    PanicBuyingCouponsDAO panicBuyingCouponsDAO;

    @Override
    public List<Coupons> findCouponsList(Coupons coupons) {
        return couponsDAO.findCouponsList(coupons);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCoupons(Coupons coupons) {
        //向优惠券库存明细中添加数据
        int Stock = coupons.getStock();
        String url = "http://yibinmall.chenglee.top:81/prod-api/mall/exchange/check/";
        coupons.setCoupon_id(IdUtil.getSnowflakeNextId()); //使用雪花ID
        coupons.setDel_flag(false);
        couponsDAO.addCoupons(coupons);
        if (Stock > 0) {
            for (int i = 0; i < Stock; i++) {
                CouponsStock couponsStock = new CouponsStock();
                couponsStock.setCoupons_id(coupons.getCoupon_id());
                couponsStock.setHave_been_sold(false);
                couponsStock.setAdd_time(new Timestamp(new Date().getTime()));
                couponsStock.setCoupons_name(coupons.getCoupon_name());
                couponsStock.setItem_id(IdUtil.getSnowflakeNextId()); //使用雪花ID
                couponsStock.setDel_flag(false);
                couponsStockDAO.addCouponsStock(couponsStock);
                couponsStock.setQr_code(url + couponsStock.getItem_id());
                couponsStockDAO.updateCouponsStock(couponsStock);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void DeleteCouponsById(long id) {
        //删除优惠券的同时，真正删除未售出的库存个体
        List<Long> unsold_coupons_item_ids = couponsStockDAO.findUnsoldItemIdsByCouponsId(id);
        if (!CollectionUtils.isEmpty(unsold_coupons_item_ids)) {
            for (Long unsold_coupons_item_id : unsold_coupons_item_ids) {
                couponsStockDAO.realDelete(unsold_coupons_item_id);
            }
        }
        //逻辑删除已售出的库存个体
        List<Long> sold_coupons_item_ids = couponsStockDAO.findSoldItemIdsByCouponsId(id);
        if (!CollectionUtils.isEmpty(sold_coupons_item_ids)) {
            for (Long sold_coupons_item_id : sold_coupons_item_ids) {
                couponsStockDAO.updateDelFlag(sold_coupons_item_id);
            }
        }
        //逻辑删除对应的抢购优惠券
        PanicBuyingCoupons byCouponsId = panicBuyingCouponsDAO.findByCoupons_id(id);
        if (byCouponsId != null) {
            byCouponsId.setDel_flag(true);
            panicBuyingCouponsDAO.updatePanicBuyingCoupons(byCouponsId);
        }
        //删除优惠券时，是逻辑删除，其实还保存在数据库中
        couponsDAO.deleteCouponsById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCoupons(Coupons coupons) {
        int couponsNewStock = coupons.getStock();
        int couponsOldStock = couponsDAO.findStockByCouponsId(coupons.getCoupon_id());
        if (couponsNewStock > couponsOldStock) {  /*如果增加库存*/
            //向优惠券库存个体表添加数据
            CouponsStock couponsStock = new CouponsStock();
            couponsStock.setCoupons_id(coupons.getCoupon_id());
            couponsStock.setHave_been_sold(false);
            couponsStock.setAdd_time(new Timestamp(new Date().getTime()));
            couponsStock.setCoupons_name(coupons.getCoupon_name());
            couponsStock.setDel_flag(false);
            int addNum = couponsNewStock - couponsOldStock;
            for (int i = 0; i < addNum; i++) {
                couponsStock.setItem_id(IdUtil.getSnowflakeNextId()); //使用雪花ID
                couponsStockDAO.addCouponsStock(couponsStock);
            }
        } else if (couponsNewStock < couponsOldStock) { /*如果减少库存*/
            int subNum = couponsOldStock - couponsNewStock;
            //找出未售出的库存个体ID
            List<Long> couponsStockIds = couponsStockDAO.findCouponsStockIds(coupons.getCoupon_id());
            if (couponsStockIds == null || couponsStockIds.size() < subNum) {
                throw new RuntimeException(MessageConstant.REDUCE_STOCK_ACTION_ERROR);
            }
            for (int i = 0; i < subNum; i++) {
                //删除
                couponsStockDAO.deleteCouponsStock(Math.toIntExact(couponsStockIds.get(i)));
            }
        }
        couponsDAO.updateCoupons(coupons);
        //如果优惠券名称发生变化，优惠券库存中的名称也随之变化
        couponsStockDAO.updateCouponName(coupons.getCoupon_name(),coupons.getCoupon_id());
    }

    /**
     * 查询总记录数
     * @return 总记录数
     */
    @Override
    public long findAllRecordNumber() {
        return couponsDAO.findAllRecordNumber();
    }

    @Override
    public Coupons findByCoupons_item_id(long coupon_item_id) {
        return couponsDAO.findByCoupons_item_id(coupon_item_id);
    }

    @Override
    public Coupons findByCouponsId(long coupons_id) {
        return couponsDAO.findByCoupon_id(coupons_id);
    }

    @Override
    public List<CouponsChooseResult> getCouponsChooseResultList() {
        List<CouponsChooseResult> couponsChooseResultList = couponsDAO.getCouponsChooseResultList();
        for (CouponsChooseResult couponsChooseResult : couponsChooseResultList) {
            int Stock1 = couponsChooseResult.getStock();
            int Stock2 = 0;
            PanicBuyingCoupons byCoupons_id = panicBuyingCouponsDAO.findByCoupons_id(couponsChooseResult.getCoupon_id());
            if (byCoupons_id != null) {
                couponsChooseResult.setStock(Stock1 + Stock2);
            } else {
                couponsChooseResult.setStock(Stock1);
            }
        }
        return couponsChooseResultList;
    }

    @Override
    public List<String> findLikeStoreName(String name) {
        return couponsDAO.findLikeStoreName(name);
    }
}
